package com.sgu6.sgu6_machine.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TempUtil {

    private static TempUtil util;
    private static SharedPreferences sp;
    private static HashMap<String, String> map = new HashMap<>();
    private static final String KEY = "TEMP_KEY";

    private TempUtil(Context context) {
        sp = context.getSharedPreferences("TEMP_PARAMS", Context.MODE_PRIVATE);
    }

    /**
     * 初始化SharedPreferencesUtil,只需要初始化一次，建议在Application中初始化
     *
     * @param context 上下文对象
     */
    public static TempUtil getInstance(Context context) {
        if (util == null) {
            util = new TempUtil(context);
        }
        return util;
    }


    /**
     * 用于保存集合
     *
     * @param map map数据
     * @return 保存结果
     */
    public boolean write(Map<String, String> map) {
        boolean result;
        SharedPreferences.Editor editor = sp.edit();
        try {
            Gson gson = new Gson();
            String json = gson.toJson(map);
            editor.putString(KEY, json);
            result = true;
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        editor.apply();
        return result;
    }

    /**
     * 用于保存集合
     *
     * @return HashMap
     */
    public HashMap<String, String> read() {
        String json = sp.getString(KEY, "");

        assert json != null;
        JsonElement element = new JsonParser().parse(json);

        if (!element.isJsonNull()) {
            JsonObject obj = element.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> entrySet = obj.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                String entryKey = entry.getKey();
                map.put(entryKey, entry.getValue().getAsString());
            }
            Log.e("WarningUtil", obj.toString());
        }

        return map;
    }

    /**
     * 增加单个数据
     *
     * @param key   单个数据key
     * @param value 单个数据value
     */
    public void add(String key, String value) {
        map.put(key, value);
        SharedPreferences.Editor editor = sp.edit();
        try {
            Gson gson = new Gson();
            String json = gson.toJson(map);
            editor.putString(KEY, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        editor.apply();
    }
}
